package com.googlecode.imanager.jasper;

import java.io.OutputStream;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperPrint;

import com.googlecode.imanager.client.Application;
import com.googlecode.imanager.client.Document;
import com.googlecode.imanager.client.Manager;
import com.googlecode.imanager.client.bridge.BridgeType;
import com.googlecode.imanager.client.event.EvaluationPhase;
import com.googlecode.imanager.core.base.DefaultManager;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class PdfApplication extends RApplication {

    public PdfApplication(DefaultManager manager, Application application, OutputStream output) {
        super(manager, application, output);
    }

    @Override
    public BridgeType getImplementationType() {
        return BridgeType.PDF;
    }

    @Override
    public void generateBridgePrint(Document document) throws Exception {        
        firePhaseEvent(document, EvaluationPhase.DOCUMENT_START);
        document.setVisible(true);
        
        RDocument report = (RDocument) Manager.getImpl(document);
        report.lockDocument(true);
        try {
            PdfPageBuilder printer = new PdfPageBuilder(report, new JasperPrint());
            printer.buildPageList(false);
    
            // TODO fazer as alterações do evento DOCUMENT_END refletirem em todas as páginas
            firePhaseEvent(document, EvaluationPhase.DOCUMENT_END);
    
            JasperExportManager.exportReportToPdfStream(printer.getPrint(), getOutput());        
        } finally {
            report.lockDocument(false);
        }
    }

}
